package ln.gather.jsr.common.util;


import javax.annotation.Priority;
import java.util.Comparator;
import java.util.Objects;

/**
 * 优先级比较器
 */
public class PriorityComparator implements Comparator<Object> {

    private final static Class<Priority> PRIORITY_CLASS = Priority.class;

    private final static int UNDEFINED_VALUE = -1;

    /**
     * 比较器实例
     */
    public final static PriorityComparator INSTANCE = new PriorityComparator();

    @Override
    public int compare(Object o1, Object o2) {
        return compare(resolveClass(o1), resolveClass(o2));
    }

    public int compare(Class<?> type1, Class<?> type2) {
        if(Objects.equals(type1, type2)) {
            return 0;
        }
        Priority priority1 = AnnotationUtils.findAnnotation(type1, PRIORITY_CLASS);
        Priority priority2 = AnnotationUtils.findAnnotation(type2, PRIORITY_CLASS);

        int priorityValue1 = getValue(priority1);
        int priorityValue2 = getValue(priority2);

        return Integer.compare(priorityValue1, priorityValue2);
    }

    private int getValue(Priority priority) {
        int value = priority == null? UNDEFINED_VALUE: priority.value();
        return value < 0? UNDEFINED_VALUE:value;
    }

    /**
     * 如果本身是class则直接返回，如果是对象则返回对象的class
     */
    private Class<?> resolveClass(Object o) {
        return o instanceof Class? (Class) o : o.getClass();
    }

}
